//
//  PPFriendSwitchViewController.m
//  pet
//
//  Created by 陈无忌 on 10/2/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPFriendIndexController.h"
//单聊
//群聊
#import "ChatViewController.h"
//群组
#import "PPGroupViewController.h"
//通知
#import "PPRequestTableTableViewController.h"
//用户
#import "PPOtherUserCardViewController.h"


#import "PPConversationCell.h"
#import "PPContactsCell.h"

#import "PPSystemConfiguraton.h"
#import "supportingHeadFiles.h"
#import "PPCustomBGTableView.h"
#import "ChineseToPinyin.h"
#import "PPApplyNotification.h"

@interface PPFriendIndexController ()<UITableViewDelegate,UITableViewDataSource,EMChatManagerDelegate>


@property (weak, nonatomic) IBOutlet UIButton *conversationButton;
@property (weak, nonatomic) IBOutlet UIButton *contactsButton;
@property (weak, nonatomic) PPSystemConfiguraton *config;

@property (strong, nonatomic) NSMutableArray *conversationArray;

@property (strong, nonatomic) NSMutableArray *sectionTitles;
@property (strong, nonatomic) NSMutableArray *dataSource;


@property (nonatomic) int type;

@property (weak, nonatomic) IBOutlet UITableView *displayTableView;

@property (nonatomic, strong) UIRefreshControl *refreshControl; //下拉刷新
@property (nonatomic) BOOL isRefresh;

@end

@implementation PPFriendIndexController
- (NSMutableArray *)sectionTitles{
    if (!_sectionTitles) {
        _sectionTitles = [NSMutableArray array];
    }
    return _sectionTitles;
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}


- (PPSystemConfiguraton *)config
{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return _config;
}

- (NSMutableArray *)conversationArray
{
    if (!_conversationArray) {
        _conversationArray = [NSMutableArray array];
    }
    return _conversationArray;
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.displayTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.displayTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.displayTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.displayTableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    //请求角标刷新
    if (self.type == 1) {
        [self.config getApplyListwithComepletion:^{
            NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
            [self.displayTableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone];
        }];
    }
    if (self.type == 0) {
        [self getConversation];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.displayTableView.delegate = self;
    self.displayTableView.dataSource = self;
    
    
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
    //注册为SDK的ChatManager的delegate
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    //button
    [self.conversationButton addTarget:self action:@selector(showConversation) forControlEvents:UIControlEventTouchUpInside];
    [self.contactsButton addTarget:self action:@selector(showContacts) forControlEvents:UIControlEventTouchUpInside];
    //0是会话 1是通讯录
    //初始化默认会话界面
    [self showConversation];
    
    //下拉刷新控件
    self.refreshControl = [[UIRefreshControl alloc] init];
    self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"正在刷新"];
    [self.refreshControl addTarget:self action:@selector(refreshTableView) forControlEvents:UIControlEventValueChanged];
    [self.displayTableView addSubview:self.refreshControl];
    self.isRefresh = NO;
}

- (void)refreshTableView{
    self.isRefresh = YES;
    if (self.type == 0) {
        [self.config getConversationListwithComepletion:^{
            [self.displayTableView reloadData];
            [self.refreshControl endRefreshing];
            self.isRefresh = NO;
        }];
    }else{
        [self.config getFriendListwithComepletion:^{
            [self.displayTableView reloadData];
            [self.refreshControl endRefreshing];
            self.isRefresh = NO;
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//获取会话列表
- (void)getConversation
{
    [self.conversationArray removeAllObjects];
    for (PPConversation *conversation in self.config.conversationArray) {
        EMMessage *msg = [conversation.conversation latestMessage];
        if (msg) {
            [self.conversationArray addObject:conversation];
        }
    }
    [self.displayTableView reloadData];
}

//获取好友列表
- (void)getContact
{
    [self.dataSource removeAllObjects];
    [self.dataSource addObjectsFromArray:[self sortDataArray:self.config.friendArray]];
    [self.displayTableView reloadData];
}


- (NSMutableArray *)sortDataArray:(NSArray *)dataArray
{
    //建立索引的核心
    UILocalizedIndexedCollation *indexCollation = [UILocalizedIndexedCollation currentCollation];
    
    [self.sectionTitles removeAllObjects];
    [self.sectionTitles addObjectsFromArray:[indexCollation sectionTitles]];
    
    //返回27，是a－z和＃
    NSInteger highSection = [self.sectionTitles count];
    //tableView 会被分成27个section
    NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:highSection];
    for (int i = 0; i <= highSection; i++) {
        NSMutableArray *sectionArray = [NSMutableArray arrayWithCapacity:1];
        [sortedArray addObject:sectionArray];
    }
    
    //名字分section
    for (PPUserInfo *buddy in dataArray) {
        //getUserName是实现中文拼音检索的核心，见NameIndex类
        NSString *firstLetter = [ChineseToPinyin pinyinFromChineseString:buddy.userName];
        NSInteger section;
        @try {
            section = [indexCollation sectionForObject:[firstLetter substringToIndex:1] collationStringSelector:@selector(uppercaseString)];
        }
        @catch (NSException * e) {
            section = 26;
        }
        
        
        NSMutableArray *array = [sortedArray objectAtIndex:section];
        [array addObject:buddy];
    }
    
    //每个section内的数组排序
    for (int i = 0; i < [sortedArray count]; i++) {
        NSArray *array = [[sortedArray objectAtIndex:i] sortedArrayUsingComparator:^NSComparisonResult(PPUserInfo *obj1, PPUserInfo *obj2) {
            NSString *firstLetter1 = [ChineseToPinyin pinyinFromChineseString:obj1.userName];
            firstLetter1 = [[firstLetter1 substringToIndex:1] uppercaseString];
            
            NSString *firstLetter2 = [ChineseToPinyin pinyinFromChineseString:obj2.userName];
            firstLetter2 = [[firstLetter2 substringToIndex:1] uppercaseString];
            
            return [firstLetter1 caseInsensitiveCompare:firstLetter2];
        }];
        
        
        [sortedArray replaceObjectAtIndex:i withObject:[NSMutableArray arrayWithArray:array]];
    }
    
    return sortedArray;
}


#pragma mark - table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.type == 0){
        return 1;
    }else{
        return self.dataSource.count + 1;
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.type == 0) {
        return self.conversationArray.count;
    }else{
        if (section == 0) {
            return 2;
        }else{
            return [[self.dataSource objectAtIndex:(section - 1)] count];
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.type == 0) {
        PPConversationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"conversationCell"];
        PPConversation *conversation = [self.conversationArray objectAtIndex:indexPath.row];
        [cell configCellWithConversation:conversation];
        return cell;
    }else{
        PPContactsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"contactCell"];
        if (indexPath.section == 0 && indexPath.row == 0) {
            cell.nameLabel.text = @"通知";
            [cell.avatar setImage:[UIImage imageNamed:@"newfriend"]];
            if (self.config.applyArray.count > 0) {
                NSMutableArray *unOperateArray = [NSMutableArray array];
                for (PPApplyNotification *request in self.config.applyArray) {
                    if (request.operate == 0) {
                        [unOperateArray addObject:request];
                    }
                }
                if(unOperateArray.count > 0){
                    cell.notificationCount.hidden = NO;
                    [cell.notificationCount setTitle:[NSString stringWithFormat:@"%d",unOperateArray.count] forState:UIControlStateNormal];
                }else{
                    cell.notificationCount.hidden = YES;
                }
            }else{
                cell.notificationCount.hidden = YES;
            }
        }else if (indexPath.section == 0 && indexPath.row == 1){
            cell.nameLabel.text = @"群聊";
            [cell.avatar setImage:[UIImage imageNamed:@"groupChatter"]];
            cell.notificationCount.hidden = YES;
        }else{
            PPUserInfo *buddy = [[self.dataSource objectAtIndex:(indexPath.section - 1)] objectAtIndex:indexPath.row];
            [cell configCellWithConversation:buddy];
        }
        return cell;
    }
    
}

#pragma mark - table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.type == 0) {
        return 67;
    }else{
        return 55;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.type == 0) {
        return 0;
    }
    if (section == 0 || [[self.dataSource objectAtIndex:(section - 1)] count] == 0)
    {
        return 0;
    }
    else{
        return 22;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    //如果是会话 不显示
    if (self.type == 0) {
        return nil;
    }
    if (section == 0 || [[self.dataSource objectAtIndex:(section - 1)] count] == 0)
    {
        return nil;
    }
    
    UIView *contentView = [[UIView alloc] init];
    [contentView setBackgroundColor:[UIColor colorWithRed:0.88 green:0.88 blue:0.88 alpha:1.0]];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 100, 22)];
    label.backgroundColor = [UIColor clearColor];
    [label setText:[self.sectionTitles objectAtIndex:(section - 1)]];
    [contentView addSubview:label];
    return contentView;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (self.type == 0) {
        return nil;
    }
    NSMutableArray * existTitles = [NSMutableArray array];
    //section数组为空的title过滤掉，不显示
    for (int i = 0; i < [self.sectionTitles count]; i++) {
        if ([[self.dataSource objectAtIndex:i] count] > 0) {
            [existTitles addObject:[self.sectionTitles objectAtIndex:i]];
        }
    }
    return existTitles;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.type == 0) {
        PPConversation *conversation = [self.conversationArray objectAtIndex:indexPath.row];
        [conversation.conversation markMessagesAsRead:YES];
        if (conversation.conversation.isGroup) {
            [[EaseMob sharedInstance].chatManager asyncSearchPublicGroupWithGroupId:conversation.targetId completion:^(EMGroup *group, EMError *error) {
                if (group && !error) {
                    ChatViewController *targetVC = [[ChatViewController alloc] initWithGroup:group];
                    conversation.chatGroup.group = group;
                    targetVC.myConversation = conversation;
                    targetVC.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:targetVC animated:YES];
                    [self getConversation];
                }
            } onQueue:nil];
        }else{
            ChatViewController *targetVC = [[ChatViewController alloc] initWithChatter:conversation.targetId];
            targetVC.myConversation = conversation;
            targetVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:targetVC animated:YES];
            [self getConversation];
        }
    }else{
        if (indexPath.section == 0 && indexPath.row == 0) {
            PPRequestTableTableViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPRequestTableTableViewController"];
            [self.navigationController pushViewController:targetVC animated:YES];
        }else if (indexPath.section == 0 && indexPath.row == 1){
            PPGroupViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPGroupViewController"];
            [self.navigationController pushViewController:targetVC animated:YES];
        }else{
            PPUserInfo *buddy = [[self.dataSource objectAtIndex:(indexPath.section - 1)] objectAtIndex:indexPath.row];
            PPOtherUserCardViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPOtherUserCardViewController"];
            targetVC.user = buddy;
            [self.navigationController pushViewController:targetVC animated:YES];
        }
    }
}

#pragma mark - 环信回调
-(void)didReceiveMessage:(EMMessage *)message{
    [self.config getConversationListwithComepletion:^{
        [self getConversation];
    }];
}

- (void)didUpdateBuddyList:(NSArray *)buddyList changedBuddies:(NSArray *)changedBuddies isAdd:(BOOL)isAdd{
    //好友列表发生变化
}



#pragma mark - Custom method
- (void)showConversation {
    self.type = 0;
    [self.conversationButton setSelected:YES];
    [self.contactsButton setSelected:NO];
    //reload tableview
    [self getConversation];
    
}


- (void)showContacts {
    self.type = 1;
    [self.conversationButton setSelected:NO];
    [self.contactsButton setSelected:YES];
    //reload tableview
    [self getContact];
}






@end
